import { useEffect, useMemo, useState, useCallback } from 'react';
import { Card, Form, Row, Col, Select, DatePicker, Input, Button, Tabs, Table, Empty, Pagination, Modal, App } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { getBindAll, getTradeList, createFenxiaoOrder, getSkuRelationTo, getSkus, saveRelationSku, type ShopData, type TradeData, type SkuDTO, type AliSkuData } from '../../services/login';



function TradeFenxiaoContent() {
  const { message } = App.useApp();
  const [shopId, setShopId] = useState<string | undefined>(undefined);
  const [timeRange, setTimeRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [oid, setOid] = useState('');
  const [title, setTitle] = useState('');
  const [status, setStatus] = useState<string>('1');
  const [data, setData] = useState<TradeData[]>([]);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [shopOptions, setShopOptions] = useState<{ label: string, value: string }[]>([]);
  const [shopLoading, setShopLoading] = useState<boolean>(false);

  // 商品选择弹窗相关状态
  const [productModalVisible, setProductModalVisible] = useState<boolean>(false);
  const [productList, setProductList] = useState<SkuDTO[]>([]);

  // 商品来源链接管理状态
  const [productLink, setProductLink] = useState<string>('');
  const [aliSkuList, setAliSkuList] = useState<AliSkuData[]>([]);
  const [syncLoading, setSyncLoading] = useState<boolean>(false);

  // SKU关联状态
  const [skuRelations, setSkuRelations] = useState<{ [key: number]: { aliSkuId: number; purchaseMultiplier: number } }>({});


  // 分销下单相关状态
  const [fenxiaoLoading, setFenxiaoLoading] = useState<{ [key: string]: boolean }>({});

  // 复制功能
  const handleCopy = (text: string, label: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success(`${label}已复制到剪贴板`);
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 从1688链接中解析offerId
  const parseOfferIdFromLink = (link: string): string | null => {
    const match = link.match(/\/offer\/(\d+)\.html/);
    return match ? match[1] : null;
  };

  // 同步SKU
  const handleSyncSku = async () => {
    if (!productLink.trim()) {
      message.warning('请先输入商品链接');
      return;
    }

    const offerId = parseOfferIdFromLink(productLink);
    if (!offerId) {
      message.error('无法从链接中解析出商品ID，请检查链接格式');
      return;
    }

    try {
      setSyncLoading(true);
      const { result: { body: { data, code } } } = await getSkus({ offerId });

      if (code === 200 && Array.isArray(data)) {
        setAliSkuList(data);
        message.success(`成功获取 ${data.length} 个SKU`);
      } else {
        message.error('获取SKU失败');
      }
    } catch (error) {
      message.error('获取SKU失败，请重试');
    } finally {
      setSyncLoading(false);
    }
  };

  // 保存SKU关联
  const handleSaveSkuRelation = async (skuId: number, aliSkuId: number, purchaseMultiplier: number) => {
    console.log("🚀 ~ handleSaveSkuRelation ~ skuId:", skuId)
    const skuItem = productList.find(item => item.skuId === skuId);
    console.log("🚀 ~ handleSaveSkuRelation ~ productList:", productList)
    const aliSkuItem = aliSkuList.find(item => item.aliSkuId === aliSkuId);
    console.log("🚀 ~ handleSaveSkuRelation ~ aliSkuList:", aliSkuList)
    console.log("🚀 ~ handleSaveSkuRelation ~ aliSkuItem:", aliSkuItem, skuItem)

    if (!skuItem || !aliSkuItem || !shopId) {
      message.error('SKU信息不完整');
      return;
    }

    try {
      const relationData = {
        shopId: shopId,
        shopName: skuItem.shopName,
        goodsId: skuItem.goodsId,
        skuImage: skuItem.skuImage,
        skuId: skuItem.skuId,
        skuDesc: skuItem.skuDesc,
        dgGoodsId: aliSkuItem.aliItemId,
        dgTitle: aliSkuItem.aliTitle,
        dgImgUrl: aliSkuItem.aliImgUrl,
        dgSkuId: String(aliSkuItem.aliSkuId),
        dgSkuDesc: aliSkuItem.aliSkuDesc,
        dgLink: productLink,
        dgPlatform: '1688',
        dgSellerId: aliSkuItem.aliSellerNick,
        dgShopName: aliSkuItem.aliSellerNick,
        dgSpecId: aliSkuItem.aliSpecid,
        dgMinnum: 1,
        isCiphertext: false
      };

      const { result: { body: { code, msg } } } = await saveRelationSku(relationData);

      if (code === 200) {
        // 更新本地关联状态
        setSkuRelations(prev => ({
          ...prev,
          [skuId]: { aliSkuId, purchaseMultiplier }
        }));
        message.success('关联保存成功');
      } else {
        message.success(msg || '保存失败');
      }
    } catch (error) {
      message.error('保存关联失败，请重试');
    }
  };

  // 处理SKU选择变化
  const handleSkuChange = (skuId: number, aliSkuId: number) => {
    // 先更新 productList 中的 dgSkuId，确保选择器能正确显示
    setProductList(prevList =>
      prevList.map(item =>
        item.skuId === skuId
          ? { ...item, dgSkuId: String(aliSkuId) }
          : item
      )
    );

    const currentRelation = skuRelations[skuId];
    const purchaseMultiplier = currentRelation?.purchaseMultiplier || 1;
    handleSaveSkuRelation(skuId, aliSkuId, purchaseMultiplier);
  };

  // 打开商品选择弹窗
  const handleOpenProductModal = async (orderKey: string) => {
    const order = data.find(item => String(item.oid) === orderKey);

    setProductModalVisible(true);

    // 如果找不到订单，直接返回
    if (!order) {
      message.error('未找到订单信息');
      return;
    }

    try {
      const params = {
        shopId: String(order.shopId),
        itemId: String(order.itemId)
      };

      const { result: { body: { data: relationData, code } } } = await getSkuRelationTo(params);

      if (code === 200 && relationData?.skuDTOList) {
        setProductList(relationData.skuDTOList);
        if (relationData?.relatedDTOList?.[0]?.linkUrl) {
          setProductLink(relationData.relatedDTOList[0].linkUrl);
        }

        // 设置已关联的SKU关系
        const existingRelations: { [key: number]: { aliSkuId: number; purchaseMultiplier: number } } = {};
        relationData.skuDTOList.forEach((sku: SkuDTO) => {
          if (sku.dgSkuId) {
            // 从 relatedDTOList 中找到对应的 dgGoodsId
            const relatedItem = relationData.relatedDTOList?.find((item: any) => item.dgGoodsId === sku.dgGoodsId);
            if (relatedItem) {
              existingRelations[sku.skuId] = {
                aliSkuId: parseInt(relatedItem.dgGoodsId),
                purchaseMultiplier: 1
              };
            }
          }
        });
        setSkuRelations(existingRelations);
      } else {
        message.warning('获取商品关联信息失败，使用模拟数据');
        // 保持模拟数据
      }
    } catch (error) {
      message.warning('获取商品关联信息失败，使用模拟数据');
      // 保持模拟数据
    }
  };


  // 获取店铺列表
  useEffect(() => {
    const fetchShopList = async () => {
      try {
        setShopLoading(true);
        const { result: { body: { data, code } } } = await getBindAll();

        if (code === 200 && Array.isArray(data)) {
          const options = data.map((shop: ShopData) => ({
            label: `${shop.shopName} (${shop.platform})`,
            value: shop.shopId
          }));
          setShopOptions(options);
        } else {
          message.error('获取店铺列表失败');
        }
      } catch (error) {
        message.error('获取店铺列表失败');
      } finally {
        setShopLoading(false);
      }
    };

    fetchShopList();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const start = dayjs().subtract(29, 'day').startOf('day');
    const end = dayjs().endOf('day');
    setTimeRange([start, end]);
  }, []);

  // 当分页或状态变化时重新获取数据
  useEffect(() => {
    if (shopId && timeRange) {
      refresh();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageNum, pageSize, status, shopId, timeRange]);

  // 页面初始化时调用接口
  useEffect(() => {
    // 等待店铺列表和时间范围都设置完成后调用接口
    if (shopOptions.length > 0 && timeRange) {
      // 如果还没有选择店铺，自动选择第一个店铺
      if (!shopId && shopOptions.length > 0) {
        setShopId(shopOptions[0].value);
      }
    }
  }, [shopOptions, timeRange, shopId]);

  // 当 productLink 发生变化时自动请求 getSkus 列表
  useEffect(() => {
    const autoSyncSku = async () => {
      if (!productLink.trim()) {
        setAliSkuList([]);
        return;
      }

      const offerId = parseOfferIdFromLink(productLink);
      if (!offerId) {
        setAliSkuList([]);
        return;
      }

      try {
        setSyncLoading(true);
        const { result: { body: { data, code } } } = await getSkus({ offerId });

        if (code === 200 && Array.isArray(data)) {
          setAliSkuList(data);
        } else {
          setAliSkuList([]);
        }
      } catch (error) {
        setAliSkuList([]);
      } finally {
        setSyncLoading(false);
      }
    };

    autoSyncSku();
  }, [productLink]);




  // 状态映射
  const getStatusDesc = (status: number) => {
    const statusMap: { [key: number]: string } = {
      0: '未知状态',
      10: '待付款',
      30: '已付款',
      40: '已发货',
      50: '已签收',
      70: '订单成功',
      80: '订单失败'
    };
    return statusMap[status] || '未知状态';
  };


  const columns = useMemo(() => [
    {
      title: '订单信息',
      key: 'orderInfo',
      render: (_: unknown, row: TradeData) => (
        <div>
          {/* 第一行：店铺订单信息和关联商品信息 */}
          <div style={{ display: 'flex', marginBottom: '12px' }}>
            {/* 左侧：店铺订单信息 */}
            <div style={{ flex: '0 0 30%', paddingRight: '16px', borderRight: '1px solid #f0f0f0' }}>
              <div style={{ fontWeight: 'bold', marginBottom: '8px', color: '#333' }}>店铺订单信息</div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px', fontSize: '12px' }}>商品图片：</span>
                <img src={row.itemPicUrl} alt={row.itemTitle} style={{ width: '100px', height: '100px', objectFit: 'cover', marginBottom: '8px' }} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px', fontSize: '12px' }}>来源店铺：</span>
                <span style={{ flex: 1, fontSize: '12px' }}>{row.shopName}</span>
                <span style={{ marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>支付时间：</span>
                <span style={{ flex: 1, fontSize: '12px' }}>{row.payTime}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>订单号：</span>
                <span style={{ flex: 1, fontSize: '12px' }}>{row.oid}</span>
                <Button
                  type="text"
                  size="small"
                  icon={<CopyOutlined />}
                  onClick={() => handleCopy(String(row.oid), '订单号')}
                  style={{ padding: '0 4px', minWidth: 'auto' }}
                />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>商品标题：</span>
                <span style={{ flex: 1, fontSize: '12px' }}>{row.itemTitle}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>SKU：</span>
                <span style={{ flex: 1, fontSize: '12px' }}>{row.skuDesc}</span>

              </div>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ color: '#1890ff', marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>状态：</span>
                <span style={{ flex: 1, color: '#1890ff', fontSize: '12px' }}>{getStatusDesc(row.status)}</span>

              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ color: '#52c41a', marginRight: '8px', fontSize: '12px', fontWeight: 'bold' }}>金额：</span>
                <span style={{ flex: 1, color: '#52c41a', fontSize: '12px', fontWeight: 'bold' }}>¥{row.totalFee}</span>

              </div>
            </div>

            {/* 右侧：关联商品信息或上家采购订单 */}
            <div style={{ flex: '0 0 70%', paddingLeft: '16px' }}>
              <div style={{ fontWeight: 'bold', marginBottom: '8px', color: '#333' }}>
                {!row.purchaseList || row.purchaseList.length === 0 ? '关联商品信息' : '上家采购订单'}
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {!row.purchaseList || row.purchaseList.length === 0 ? (
                  // 无采购订单时显示关联商品信息
                  row.relationObj ? (
                    <>
                      <img
                        src={row.relationObj.dgImgUrl}
                        alt={row.relationObj.dgTitle}
                        style={{ width: '60px', height: '60px', objectFit: 'cover', marginRight: '12px', borderRadius: '4px' }}
                      />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 'bold', marginBottom: '4px', lineHeight: '1.4', fontSize: '12px' }}>
                          {row.relationObj.dgTitle}
                        </div>
                        <div style={{ color: '#666', fontSize: '11px', marginBottom: '4px' }}>
                          供应商：{row.relationObj.dgSellerNick}
                        </div>
                        <div style={{ color: '#666', fontSize: '11px', marginBottom: '4px' }}>
                          商品ID：{row.relationObj.dgItemId}
                        </div>
                        <div style={{ color: '#666', fontSize: '11px', marginBottom: '8px' }}>
                          SKU：{row.relationObj.dgSkuDesc}
                        </div>
                        <div>
                          <Button
                            type="link"
                            size="small"
                            onClick={() => handleOpenProductModal(String(row.oid))}
                            style={{ padding: 0, fontSize: '11px', height: 'auto' }}
                          >
                            修改关联
                          </Button>
                        </div>
                      </div>
                    </>
                  ) : (
                    <div style={{ flex: 1, textAlign: 'center' }}>
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => handleOpenProductModal(String(row.oid))}
                        style={{ backgroundColor: '#ff6900', borderColor: '#ff6900' }}
                      >
                        去关联商品
                      </Button>
                    </div>
                  )
                ) : (
                  // 有采购订单时显示上家采购订单信息
                  row.purchaseList && row.purchaseList.length > 0 ? (
                    <div style={{ flex: 1 }}>
                      {(() => {
                        const purchase = row.purchaseList[0];
                        return (
                          <>
                            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                              <img
                                src={purchase.dgItemPic}
                                alt={purchase.dgItemTitle}
                                style={{ width: '50px', height: '50px', objectFit: 'cover', marginRight: '12px', borderRadius: '4px' }}
                              />
                              <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 'bold', marginBottom: '4px', lineHeight: '1.4', fontSize: '12px' }}>
                                  {purchase.dgItemTitle}
                                </div>
                                <div style={{ color: '#666', fontSize: '11px', marginBottom: '2px' }}>
                                  代购订单号：{purchase.dgOid}
                                </div>
                                <div style={{ color: '#666', fontSize: '11px', marginBottom: '2px' }}>
                                  拍单号：{purchase.dgUser}
                                </div>
                              </div>
                            </div>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', fontSize: '11px', color: '#666' }}>
                              <div>代购平台：{purchase.dgPlatform}</div>
                              <div>代购状态：{purchase.status}</div>
                              <div>代购价格：¥{purchase.dgPayment}</div>
                              <div>代购件数：{purchase.dgNum}</div>
                              <div>买家昵称：{purchase.dgPlatformBuyerNick}</div>
                              <div>卖家昵称：{purchase.dgPlatformSellerNick}</div>
                              <div>商品ID：{purchase.dgItemId}</div>
                              <div>SKU ID：{purchase.dgSkuId}</div>
                              <div>SKU描述：{purchase.dgSkuDesc}</div>
                              <div>检测状态：{purchase.checkStatus}</div>
                              {purchase.dgExpressNo && (
                                <div>物流单号：{purchase.dgExpressNo}</div>
                              )}
                              {purchase.dgExpressName && (
                                <div>物流公司：{purchase.dgExpressName}</div>
                              )}
                              {purchase.relMobile && (
                                <div>买家手机：{purchase.relMobile}</div>
                              )}
                              <div>支付时间：{purchase.payTime}</div>
                              {purchase.checkTime && (
                                <div>检测时间：{purchase.checkTime}</div>
                              )}
                              <div>是否分销：{purchase.isFenxiao ? '是' : '否'}</div>
                              <div>售后完成：{purchase.afterSaleComplete ? '是' : '否'}</div>
                              {purchase.sendSms && (
                                <div>已发送短信：{purchase.sendSms ? '是' : '否'}</div>
                              )}
                            </div>
                          </>
                        );
                      })()}
                    </div>
                  ) : (
                    <div style={{ flex: 1, textAlign: 'center', color: '#999', fontSize: '12px' }}>
                      暂无采购订单信息
                    </div>
                  )
                )}
              </div>
            </div>
          </div>
          {/* 第三行：收货地址和分销下单按钮 */}
          <div style={{
            padding: '12px',
            backgroundColor: '#f8f9fa',
            borderRadius: '6px',
            border: '1px solid #e9ecef',
            marginTop: '8px'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ flex: 1 }}>
                <div style={{ marginBottom: '6px', fontWeight: 'bold', color: '#333', fontSize: '13px' }}>
                  收货地址：
                </div>
                <div style={{ color: '#666', lineHeight: '1.4', fontSize: '12px' }}>
                  {row.address}
                </div>
              </div>
              <div style={{ marginLeft: '20px' }}>
                {status === '1' && (
                  <Button
                    type="primary"
                    size="small"
                    loading={fenxiaoLoading[row.oid]}
                    onClick={() => handleFenxiaoOrder(row)}
                    disabled={!row.relationObj}
                  >
                    分销下单
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      ),
    }
  ], [fenxiaoLoading, handleOpenProductModal]); // eslint-disable-line react-hooks/exhaustive-deps

  const refresh = useCallback(async () => {
    // 校验
    if (!shopId) {
      message.warning('请选择店铺!');
      return;
    }
    if (!timeRange) {
      message.warning('请选择成交时间段!');
      return;
    }

    // 如果当前没有数据，先设置模拟数据


    try {
      setLoading(true);

      // 状态映射
      const statusMap: { [key: string]: string } = {
        '1': '待采购',
        '2': '待发货',
        '3': '退款中',
        '4': '已发货',
        '5': '交易成功',
        '0': '全部'
      };

      const params = {
        tagName: statusMap[status] || '全部',
        shopId,
        startTime: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
        endTime: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
        oid: oid || '',
        title: title || '',
        pageNum: String(pageNum),
        pageSize: String(pageSize)
      };

      const { result: { body: { data: listData, code, totalCount } } } = await getTradeList(params);

      if (code === 200 && Array.isArray(listData)) {
        setData(listData);
        setTotal(totalCount || 0);
      } else {
        message.error('获取订单列表失败');
        // 不设置空数据，保持现有数据
      }
    } catch (error) {
      message.error('获取订单列表失败');
      // 不设置空数据，保持现有数据
    } finally {
      setLoading(false);
    }
  }, [shopId, timeRange, status, pageNum, pageSize, oid, title, message]);

  // 快速设置时间范围
  const handleQuickTimeRange = (days: number) => {
    const end = dayjs().endOf('day');
    const start = dayjs().subtract(days - 1, 'day').startOf('day');
    setTimeRange([start, end]);
  };

  // 分销下单
  const handleFenxiaoOrder = async (order: TradeData) => {
    // 检查是否有关联商品
    if (!order.relationObj) {
      message.warning('请先关联商品再进行分销下单');
      return;
    }

    try {
      setFenxiaoLoading(prev => ({ ...prev, [order.oid]: true }));
      const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
      const orderData = {
        shopId: String(order.shopId),
        oid: String(order.oid),
        coid: '', // 下游子订单号，暂时为空
        itemId: String(order.itemId),
        dgItemId: order.relationObj.dgItemId,
        dgTitle: order.relationObj.dgTitle,
        dgImgUrl: order.relationObj.dgImgUrl,
        dgSkuId: order.relationObj.dgSkuId,
        dgSkuDesc: order.relationObj.dgSkuDesc,
        dgSpecid: order.relationObj.dgSpecid,
        dgNum: 1, // 默认传1
        isCiphertext: false, // 固定值
        dgPlatformUserId: userInfo.userId, // TODO: 需要从用户信息中获取
        dgPlatformUserName: userInfo.userName, // TODO: 需要从用户信息中获取
        dgSellerNick: '', // 默认空即可
        isPay: false, // 固定值
        flow: 'fenxiaonew' // 代发下单
      };

      const { result: { body: { code, msg } } } = await createFenxiaoOrder(orderData);

      if (code === 200) {
        message.success('分销下单成功');
        // 可以在这里刷新订单列表或更新订单状态
        refresh();
      } else {
        message.success(msg || '分销下单失败');
      }
    } catch (error) {
      message.error('分销下单失败，请重试');
    } finally {
      setFenxiaoLoading(prev => ({ ...prev, [order.oid]: false }));
    }
  };

  return (
    <div className="trade-fenxiao-page">
      <Card style={{ marginBottom: 8 }}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="来源店铺">
                <Select
                  allowClear
                  placeholder="请选择一个店铺"
                  value={shopId}
                  onChange={setShopId}
                  options={shopOptions}
                  loading={shopLoading}
                  disabled={shopLoading}
                />
              </Form.Item>
            </Col>
            <Col span={9}>
              <Form.Item label="成交时间">
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <DatePicker.RangePicker
                    showTime
                    value={timeRange}
                    onChange={(v) => setTimeRange(v as [Dayjs, Dayjs] | null)}
                    style={{ flex: 1 }}
                  />
                  <Button 
                    size="small" 
                    onClick={() => handleQuickTimeRange(7)}
                    style={{ fontSize: '12px' }}
                  >
                    近7天
                  </Button>
                  <Button 
                    size="small" 
                    onClick={() => handleQuickTimeRange(30)}
                    style={{ fontSize: '12px' }}
                  >
                    近30天
                  </Button>
                </div>
              </Form.Item>
            </Col>
            <Col span={7}>
              <Form.Item label="卖出单号">
                <Input placeholder="请输入订单号" value={oid} onChange={(e) => setOid(e.target.value)} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="商品标题">
                <Input placeholder="请输入商品标题" value={title} onChange={(e) => setTitle(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={8} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Form.Item>
                <Button type="primary" onClick={refresh}>查询</Button>
              </Form.Item>
            </Col>
            <Col span={8} />
          </Row>
        </Form>
      </Card>

      <Card>
        <Tabs activeKey={status} onChange={setStatus}
          items={[
            { key: '1', label: '待采购' },
            { key: '2', label: '待发货' },
            { key: '3', label: '退款中' },
            { key: '4', label: '已发货' },
            { key: '5', label: '交易成功' },
            { key: '0', label: '全部' },
          ]}
        />
        <Table
          dataSource={data}
          columns={columns}
          pagination={false}
          loading={loading}
          locale={{ emptyText: <Empty description="暂无数据" /> }}
          scroll={{ y: 480 }}
          rowKey="oid"
        />
        <div style={{ marginTop: 8, textAlign: 'right' }}>
          <Pagination
            size="small"
            showSizeChanger
            pageSizeOptions={[20, 50, 100, 200]}
            current={pageNum}
            pageSize={pageSize}
            total={total}
            onChange={(p) => setPageNum(p)}
            onShowSizeChange={(_, s) => setPageSize(s)}
          />
        </div>
      </Card>

      {/* 商品选择弹窗 */}
      <Modal
        title="关联货源SKU: 袜子收纳神器内衣收纳袋壁挂式网兜内裤衣柜悬挂分格省空间整理盒"
        open={productModalVisible}
        onCancel={() => {
          setProductModalVisible(false);
          refresh(); // 关闭弹窗时刷新订单接口
        }}
        width={1400}
        footer={[
          <Button key="cancel" onClick={() => {
            setProductModalVisible(false);
            refresh(); // 关闭弹窗时刷新订单接口
          }}>
            关闭
          </Button>,
        ]}
      >
        <div style={{ padding: '20px 0' }}>
          {/* 上方：商品来源链接管理 */}
          <div style={{ marginBottom: '30px' }}>
            <div style={{ marginBottom: '16px', fontWeight: 'bold', fontSize: '16px' }}>
              商品来源链接管理
            </div>
            <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px' }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '80px 1fr 200px 200px',
                backgroundColor: '#fafafa',
                borderBottom: '1px solid #d9d9d9',
                padding: '12px 16px',
                fontWeight: 'bold',
                fontSize: '14px'
              }}>
                <div>编号</div>
                <div>商品来源链接</div>
                <div>操作</div>
              </div>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '80px 1fr 200px 200px',
                padding: '12px 16px',
                borderBottom: '1px solid #f0f0f0',
                alignItems: 'center'
              }}>
                <div>1</div>
                <div style={{ fontSize: '12px', color: '#666', width: '90%' }}>
                  <Input
                    placeholder="商品链接"
                    size="small"
                    value={productLink}
                    onChange={(e) => setProductLink(e.target.value)}
                  />
                </div>
                <div style={{ display: 'flex', gap: '8px' }}>
                  <Button
                    type="primary"
                    size="small"
                    loading={syncLoading}
                    onClick={handleSyncSku}
                  >
                    同步SKU
                  </Button>
                </div>
              </div>
            </div>
          </div>

          {/* 下方：SKU关联列表 */}
          <div>
            <div style={{ marginBottom: '16px', fontWeight: 'bold', fontSize: '16px' }}>
              SKU关联列表
            </div>
            <div style={{ border: '1px solid #d9d9d9', borderRadius: '6px', overflow: 'auto', height: '50vh' }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr 120px',
                backgroundColor: '#fafafa',
                borderBottom: '1px solid #d9d9d9',
                padding: '12px 16px',
                fontWeight: 'bold',
                fontSize: '14px'
              }}>
                <div>本店商品SKU</div>
                <div>上家商品SKU</div>
                <div>采购倍数</div>
              </div>

              {/* 渲染SKU列表 */}
              {productList.map((item, index) => (
                <div key={item.skuId} style={{
                  display: 'grid',
                  gridTemplateColumns: '1fr 1fr 120px',
                  padding: '12px 16px',
                  borderBottom: index < productList.length - 1 ? '1px solid #f0f0f0' : 'none',
                  alignItems: 'center'
                }}>
                  {/* 本店商品SKU */}
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <img
                      src={item.skuImage}
                      alt="SKU图片"
                      style={{ width: '50px', height: '50px', objectFit: 'cover', borderRadius: '4px', marginRight: '12px' }}
                    />
                    <div>
                      <div style={{ fontSize: '12px', lineHeight: '1.4', marginBottom: '4px' }}>
                        {item.skuDescMain}
                      </div>
                      <div style={{ fontSize: '11px', color: '#666' }}>
                        {item.skuDescVice}
                      </div>
                    </div>
                  </div>

                  {/* 上家商品SKU */}
                  <div>
                    <Select
                      placeholder="请选择SKU"
                      style={{ width: '90%' }}
                      size="small"
                      value={item.dgSkuId ? Number(item.dgSkuId) : undefined}
                      onChange={(value) => handleSkuChange(item.skuId, value)}
                      options={aliSkuList.map(aliSku => ({
                        label: `${aliSku.aliSkuDesc}`,
                        value: Number(aliSku.aliSkuId)
                      }))}
                    />
                  </div>

                  {/* 采购倍数 */}
                  <div>
                    1
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default function TradeFenxiao() {
  return (
    <App>
      <TradeFenxiaoContent />
    </App>
  );
}
